<html>
<header>
<script>
var sendXHR = function(params) {
  var xhr = new XMLHttpRequest();
  xhr.open('GET', params)
  xhr.send();
}

var onChange = function() {
  sendXHR('/rename/' + this.id + '/' + this.value);
  this.id = this.value;
  if (!this.id)
    this.remove();
}

var createElement = function(name) {
  var i = document.createElement('input');
  i.id = i.value = name;
  i.onchange = onChange;
  var d = document.getElementById('all_items');
  d.appendChild(i);
}

var requestData = function() {
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
    if (this.readyState == this.DONE) {
      parsed = JSON.parse(this.response);
      for (var item in parsed) {
        createElement(parsed[item]);
      }
    }
  }
  xhr.open('GET', '/dnames')
  xhr.send();
}

function dump() {
  sendXHR('/dall');
}

function setCode(o) {
  sendXHR('/setcode/' + o.value);
  var d = document.getElementById('all_items');
  d.innerHTML = '';
  requestData();
}

function setMacro(o) {
  sendXHR('/setmacro/' + o.value);
  var d = document.getElementById('all_items');
  d.innerHTML = '';
  requestData();
}

function learn() {
  sendXHR('/learn');
  var d = document.getElementById('all_items');
  var ticker = {};
  ticker.count = 0;
  ticker.timeoutid = setInterval(function() {
    d.innerHTML = 'Learning ' + ticker.count + ' of 3.';
    if (++ticker.count == 3) {
      clearTimeout(ticker.timeoutid);
      d.innerHTML = '';
      requestData();
    }
  }, 1000, ticker);
}
function sendTest() {
  var d = document.getElementById('test_cmd');
  if (d.value)
    sendXHR('/send/' + d.value);
}
</script>
</header>
<body onload="requestData()">
<input type="button" value="Learn" onclick="learn()"><br/>
<input type="button" value="Dump" onclick="dump()"><br/>
Set code (format: name/type/hex value/numbits)
<input type="input" onchange="setCode(this)"><br/>
Set macro (format: macro/cmd1/cmd2/.../cmdN)
<input type="input" onchange="setMacro(this)"><br/>
<input type="input" id="test_cmd">
<input type="button" value="Test" onclick="sendTest()"><br/>
<div id="all_items"></div>
</body>
</html>
